package com.jiufen.Service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Console;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jiufen.Mapper.EmpLogMapper;
import com.jiufen.Mapper.EmpMapper;
import com.jiufen.Pojo.*;
import com.jiufen.Service.EmpLogService;
import com.jiufen.Service.EmpService;
import com.jiufen.Utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private EmpLogService empLogService;

    //必须被spring 容器管理 才可以获取value yml 参数  使用自动注入才可以  自己new一个不行
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 分页查询方法
     */
    public PageResult<Emp> getEmpList(Integer start, Integer pageSize) {
        //1.查询总记录数
        Long total = empMapper.getCount();
        log.info("总记录数为：{}", total);

        //2.调用mapper查询结果
        //获取起始索引
        Integer startIndex = (start - 1) * pageSize;
        List<Emp> rows = empMapper.getEmpListByPage(startIndex, pageSize);

        //封装结果
        PageResult<Emp> pageResult = new PageResult<>(total, rows);
        /**
         PageResult<Emp> pageResult = new PageResult<>();
         pageResult.setTotal(total);
         pageResult.setRows(rows);
         */
        return pageResult;
    }


    public PageResult<Emp> getEmpListPage(EmpQueryParam empQueryParam) {

        //设置分页参数
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());
        //执行查询
        List<Emp> empList = empMapper.getEmpListByPageNew(empQueryParam);
        log.info("empList：{}", empList);
        //封装结果
        Page<Emp> empList1 = (Page<Emp>) empList;
        log.info("总记录数：{}", empList1.getTotal());
        log.info("总页数：{}", empList1.getPages());
        log.info("当前页：{}", empList1.getPageNum());
        log.info("每页记录数：{}", empList1.getPageSize());
        log.info("当前页记录数：{}", empList1.getResult());
        return new PageResult<Emp>(empList1.getTotal(), empList1.getResult());
    }


    /**
     * 保存员工信息  操作两次数据库  开始事务
     *
     * @param emp
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public Integer saveEmp(Emp emp) throws Exception {
        Integer i  = 0;
        Integer j = 0;
        Integer logNumber = 0;
        try {
            //1.保存员工信息
            log.info("保存员工信息={}", emp);
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            i = empMapper.saveEmp(emp);
            log.debug("返回ID的员工信息是={}", emp);
           /* if (true){
                throw new Exception("事务阻断测试--报错啦---");
            }*/

            //2.保存员工工作经历信息
            List<EmpExpr> exprList = emp.getExprList();
            log.info("保存员工工作经历信息:{}", exprList);
            if (!CollectionUtils.isEmpty(exprList)) {
                //遍历集合  赋值 关联ID
                exprList.forEach(expr -> {
                    expr.setEmpId(emp.getId());
                });
                j = empMapper.insertEmpExprBatch(emp.getExprList());
            }
        } finally {
            //3.记录操作日志
            EmpLog empLog = new EmpLog(null, LocalDateTime.now(), "保存员工信息:" + emp);
            logNumber = empLogService.insertEmpLog(empLog);
        }



        return i + j + logNumber;
    }


    /**
     * 删除员工信息和员工经历信息
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public Integer deleteEmp(List<Integer> ids) {
        //1.删除员工信息
        Integer e = empMapper.deleteEmpById(ids);
        //2.删除员工工作经历信息
        Integer expr =  empMapper.deleteEmpExprByEmpId(ids);
        return e+expr;
    }

    @Override
    public Emp getEmpById(Integer id) {
        Emp emp = empMapper.getEmpById(id);
        return emp;
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public Integer updateEmp(Emp emp) {
        //1.根据ID修改员工信息
        emp.setUpdateTime(LocalDateTime.now());  //修改操作时间
        Integer i = empMapper.updateEmpById(emp);
        //2.根据ID修改员工信息
        //2.1先删除工作经历
         empMapper.deleteEmpExprByEmpId(Arrays.asList(emp.getId()));
        //2.2 保存工作经历
        List<EmpExpr> exprList = emp.getExprList();
        //绑定员工ID
        if (!CollectionUtils.isEmpty(exprList))
        {
            exprList.forEach(expr -> {
                expr.setEmpId(emp.getId());
            });
            log.debug("exprList：{}",exprList);
            empMapper.insertEmpExprBatch(exprList);
        }

        return i;
    }

    //查询全部员工信息 无参数
    @Override
    public List<Emp> getEmpListNew() {
        List<Emp> empList = empMapper.getEmpListNew();
        return empList;
    }

    @Override
    public LoginInfo getEmpByUsernameAndPassword(Emp emp) {
        //调用mapper查询员工信息
        Emp emp1 = empMapper.getEmpByUsernameAndPassword(emp);

        //判断是否有该员工存在 有则组装信息
        if(emp1 != null){
            log.debug("获取员工登录信息成功 --- emp1={}",emp1);
            //生成JWT令牌
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",emp1.getId());
            claims.put("username",emp1.getUsername());
            String jwt = jwtUtils.createJwt(claims);
            LoginInfo loginInfo = new LoginInfo(emp1.getId(), emp1.getName(), jwt, emp1.getUsername());
            log.info("获取员工登录信息成功！{}",loginInfo);
            return loginInfo;
        }
        //不存在返回null
        return null;
    }
}
